package com.study.demo.ui.login;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.stduy.injector.PerActivity;
import com.study.demo.Constants;
import com.study.demo.api.game.GameApi;
import com.study.demo.bean.LoginResult;
import com.study.demo.bean.UserResult;
import com.study.demo.components.storage.UserStorage;
import com.study.demo.db.User;
import com.study.demo.event.LoginSuccessEvent;
import com.study.demo.greendao.UserDao;
import com.study.demo.util.SecurityUtil;
import com.study.demo.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@PerActivity
public class LoginPresenter implements LoginContract.Presenter {

    private GameApi mGameApi;
    private EventBus eventBus;
    private UserDao mUserDao;
    private UserStorage mUserStorage;

    private LoginContract.View mLoginView;
    private User user = new User();
    private Disposable disposable;

    @Inject
    public LoginPresenter(GameApi gameApi, EventBus eventBus, UserDao userDao, UserStorage userStorage) {
        mGameApi = gameApi;
        this.eventBus = eventBus;
        mUserDao = userDao;
        mUserStorage = userStorage;
    }

    @Override
    public void login(final String userName, final String passWord) {
        if (TextUtils.isEmpty(userName)) {
            mLoginView.showUserNameError("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(passWord)) {
            mLoginView.showPassWordError("请输入密码");
            return;
        }
        mLoginView.showLoading();
        disposable = mGameApi.login(userName, SecurityUtil.getMD5(passWord))
                .flatMap(loginData -> {
                    if (loginData != null && loginData.is_login == 1) {
                        LoginResult data = loginData.result;
                        String cookie = "";
                        try {
                            cookie = URLDecoder.decode(Constants.Cookie, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        String uid = cookie.split("\\|")[0];
                        user.setUid(uid);
                        user.setToken(data.token);
                        user.setCookie(cookie);
                        user.setUserName(data.username);
                        return mGameApi.getUserInfo(uid);
                    }
                    return null;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userData -> {
                    if (userData != null && userData.result != null) {
                        UserResult data = userData.result;
                        user.setIcon(data.header);
                        user.setThreadUrl(data.bbs_msg_url);
                        user.setPostUrl(data.bbs_post_url);
                        user.setRegisterTime(data.reg_time_str);
                        user.setSchool(data.school);
                        user.setSex(data.gender);
                        user.setLocation(data.location_str);
                        mUserStorage.login(user);
                        insertOrUpdateUser(user);
                        ToastUtil.showToast("登录成功");
                        eventBus.post(new LoginSuccessEvent());
                        mLoginView.loginSuccess();
                    } else {
                        mLoginView.hideLoading();
                        ToastUtil.showToast("登录失败，请检查您的网络");
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    mLoginView.hideLoading();
                    ToastUtil.showToast("登录失败，请检查您的网络");
                });
    }

    private void insertOrUpdateUser(User user) {
        List<User> users =
                mUserDao.queryBuilder().where(UserDao.Properties.Uid.eq(user.getUid())).list();
        if (!users.isEmpty()) {
            user.setId(users.get(0).getId());
        }
        mUserDao.insertOrReplace(user);
    }

    @Override
    public void attachView(@NonNull LoginContract.View view) {
        mLoginView = view;
    }

    @Override
    public void detachView() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        mLoginView = null;
    }
}
